package cn.workreport.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.exceptions.POIException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.InputStream;

/**
 * 描述【】
 *
 * @author lihuanyao
 * @time 2021/11/26 22:12
 */
public class WorkbookUtil {
    /**
     *  创建Excel操作类
     * @param isXlsx
     * @return
     */
    public static Workbook createBook(boolean isXlsx) {
        Object workbook;
        if (isXlsx) {
            workbook = new XSSFWorkbook();
        } else {
            workbook = new HSSFWorkbook();
        }

        return (Workbook)workbook;
    }

    public static Workbook createBook(InputStream in, boolean closeAfterRead) {
        return createBook(in, (String)null, closeAfterRead);
    }

    public static Workbook createBook(InputStream in, String password, boolean closeAfterRead) {
        Workbook workbook;
        try {
            workbook = WorkbookFactory.create(IoUtil.toMarkSupportStream(in), password);
        } catch (Exception e) {
            throw new POIException(e);
        } finally {
            if (closeAfterRead) {
                IoUtil.close(in);
            }

        }

        return workbook;
    }

    public static Workbook createBook(String excelFilePath) {
        return createBook(FileUtil.file(excelFilePath), (String)null);
    }

    public static Workbook createBook(File excelFile, String password) {
        try {
            return WorkbookFactory.create(excelFile, password);
        } catch (Exception e) {
            throw new POIException(e);
        }
    }
}
